import { ref, reactive, shallowRef } from 'vue'
import * as echarts from 'echarts'
import getInitOption from '../options/DiffPressureOption'
import { getSingleColor } from '../utils/colorUtils'

const chartInstance = shallowRef() // 图表实例
const allDiffPressure = reactive([]) // 数据
const config = ref({ max: 10000, min: 0 }) // 图表配置
const titleFontSize = ref(0) // 图表字体大小
const diffPressureRef = shallowRef()

function registerDiffPressure(diffPressure) {
  diffPressureRef.value = diffPressure
}
function initChart() {
  chartInstance.value = echarts.init(diffPressureRef.value, 'dark')
  chartInstance.value.setOption(getInitOption(config.value))
}
function screenAdapter() {
  titleFontSize.value = (diffPressureRef.value.offsetWidth / 100) * 4
  const progressWidth = titleFontSize.value * 2
  const axisTickLength = titleFontSize.value * 0.5
  const splitLineLength = titleFontSize.value
  const axisLabelDistance = titleFontSize.value
  const detailLineHeight = titleFontSize.value * 2
  const apdaterOption = {
    series: [
      {
        progress: {
          width: progressWidth
        },
        axisLine: {
          lineStyle: {
            width: progressWidth
          }
        },
        axisTick: {
          distance: -(progressWidth + axisTickLength),
          length: axisTickLength
        },
        splitLine: {
          distance: -(progressWidth + splitLineLength),
          length: splitLineLength
        },
        axisLabel: {
          distance: -axisLabelDistance,
          fontSize: titleFontSize.value * 1.5
        },
        detail: {
          lineHeight: detailLineHeight,
          fontSize: titleFontSize.value * 2
        }
      }
    ]
  }
  chartInstance.value.setOption(apdaterOption)
  chartInstance.value.resize()
}
function updateDiffPressure(data, status) {
  const diffPressureData = {
    value: data,
    itemStyle: {
      color: status === 1 ? getSingleColor(9) : getSingleColor(2)
    }
  }
  allDiffPressure[0] = diffPressureData
  updateDiffPressureChart()
}
function updateDiffPressureChart() {
  const dataOption = {
    series: [
      {
        data: allDiffPressure
      }
    ]
  }
  chartInstance.value.setOption(dataOption)
}

export const useDiffPressure = () => {
  return {
    registerDiffPressure,
    initChart,
    screenAdapter,
    updateDiffPressure
  }
}
